package com.sy.live.main.thread.nba;

import java.sql.Timestamp;

import org.apache.log4j.Logger;

import com.sy.live.entity.TbVideoLink;
import com.sy.live.entity.constant.CategoryConstant;
import com.sy.live.entity.constant.HttpConstant;
import com.sy.live.service.ILinkService;
import com.sy.live.util.DateUtil;
import com.sy.live.util.GetIp;
import com.sy.live.util.HttpUtil;
import com.sy.live.util.SpringBeans;
import com.sy.live.util.XMLConfigUtil;

public class GetLinkByNBA98 extends Thread
{
	private static long millis = Long.parseLong(XMLConfigUtil.getSysProperty("thread.GetLinkByNBA98")) * 1000 * 60L;
	private static Logger logger = Logger.getLogger(GetLinkByNBA98.class);
	private static String uri = "http://www.nba98.com/nbalx/";
	private static ILinkService linkService = SpringBeans.getBeanByType(ILinkService.class);
	
	@Override
	public void run()
	{
		while(true)
		{
			//获得NBA98连接的主方法
			getLinkAndSaveToDB();
			//获得历史NBA98连接的方法
//			getHistoryLinkAndSaveToDB();
			try
			{
				sleep(millis);
			} catch (InterruptedException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 获得NBA98链接的主方法
	 */
	private void getLinkAndSaveToDB()
	{
		//通过GET方法获得网页内容
		String body = HttpUtil.getResponseBodyByGetMethod(uri, HttpConstant.GB2312);
		
		if(body == null || body.trim().equals(""))
		{
			logger.info("扫描网页返回内容为空.");
			return;
		}else
		{
			String line[] = body.split("\n");
			
			for(String t : line)
			{
				if(t.contains("月") && t.contains("日") && t.contains("nbalx"))
				{
					String dateStr = t.substring(t.indexOf("月") - 2, t.indexOf("日") + 1);
					String superLink = uri + t.substring(t.indexOf("nbalx") + 6, t.indexOf("html") + 4);
					String content = "";
					
					//由于网页上显示时间不一致所以造成一下判断
					//例如:04月06日 4月6日 NBA常规赛 雷霆vs步行者 全场录像回放 
					//其中后者的4和6前面都没有0
					int month = Integer.parseInt(t.substring(t.indexOf("月") - 2, t.indexOf("月")));
					int dayOfMonth = Integer.parseInt(t.substring(t.indexOf("日") - 2, t.indexOf("日")));
					String otherDateStr = month + "月" + dayOfMonth + "日";
					
					content = t.substring(t.lastIndexOf(otherDateStr) + otherDateStr.length(), t.indexOf("</a>")).trim();
					
					//如果解析不正确，则寻找下一条记录
					if(content.contains("nbalx"))
						continue;
					
					//加上年份
					dateStr = DateUtil.getIntYearNow() + "年" + dateStr;
					
					//通过内容和子类ID判断是否存在该记录
					TbVideoLink link = linkService.findRecordByContentAndCategoryId(CategoryConstant.BASKETBALL, content);
					
					if(link != null)
					{
						if(!link.getContent().equals(content))
						{
							link.setContent(content);
							link.setDetail(t.trim());
							
							linkService.updateEntity(link);

							logger.info("视频日期[" + dateStr + "];链接地址[" + superLink + "];链接内容[" + content + "]的记录更新成功.");
						}
						
						logger.info("视频日期[" + dateStr + "];链接地址[" + superLink + "];链接内容[" + content + "]的记录已经添加.");
						
						continue;
					}else
					{
						Timestamp currentTimestamp = new Timestamp(System.currentTimeMillis());
						
						link = new TbVideoLink();
						
						link.setAddTime(currentTimestamp);
						link.setContent(content);
						link.setUpdateTime(currentTimestamp);
						link.setDetail(t.trim());
						link.setPlayTime(new Timestamp(DateUtil.parseChinaDate(dateStr).getTime()));
						link.setSuperLink(superLink);
						link.setVisited(0);
						link.setAddIp(GetIp.getLocalIp());
						link.setCategoryId(CategoryConstant.BASKETBALL);
						
						//添加记录
						linkService.addEntity(link);
						
						logger.info("视频日期[" + dateStr + "];链接地址[" + superLink + "];链接内容[" + content + "]的记录添加成功.");
					}
				}
			}
		}
	}
	
	/**
	 * 获得历时NBA98链接的主方法
	 */
	@SuppressWarnings("unused")
	private void getHistoryLinkAndSaveToDB()
	{
		int totalPage = 85;
		boolean flag = false;
		int year = DateUtil.getIntYearNow();
		
		for(int i = 1; i < totalPage; i++)
		{
			//通过GET方法获得网页内容
			String body = HttpUtil.getResponseBodyByGetMethod("http://www.nba98.com/nbalx/list_175_" + i + ".html", HttpConstant.GB2312);
			
			flag = false;
			
			if(body == null || body.trim().equals(""))
			{
				logger.info("扫描网页返回内容为空.");
				return;
			}else
			{
				String line[] = body.split("\n");
				
				for(String t : line)
				{
					if(t.contains("月") && t.contains("日") && t.contains("nbalx"))
					{
						String dateStr = t.substring(t.indexOf("月") - 2, t.indexOf("日") + 1);
						String superLink = uri + t.substring(t.indexOf("nbalx") + 6, t.indexOf("html") + 4);
						String content = "";
						
						//由于网页上显示时间不一致所以造成一下判断
						//例如:04月06日 4月6日 NBA常规赛 雷霆vs步行者 全场录像回放 
						//其中后者的4和6前面都没有0
						int month = Integer.parseInt(t.substring(t.indexOf("月") - 2, t.indexOf("月")));
						int dayOfMonth = Integer.parseInt(t.substring(t.indexOf("日") - 2, t.indexOf("日")));
						String otherDateStr = month + "月" + dayOfMonth + "日";
						
						content = t.substring(t.lastIndexOf(otherDateStr) + otherDateStr.length(), t.indexOf("</a>")).trim();
						
						//如果解析不正确，则寻找下一条记录
						if(content.contains("nbalx"))
							continue;
						
						//通过内容和子类ID判断是否存在该记录
						TbVideoLink link = linkService.findRecordByContentAndCategoryId(CategoryConstant.BASKETBALL, content);
						
						if(link != null)
						{
							if(!link.getContent().equals(content))
							{
								link.setContent(content);
								link.setDetail(t.trim());
								
								linkService.updateEntity(link);

								logger.info("视频日期[" + dateStr + "];链接地址[" + superLink + "];链接内容[" + content + "]的记录更新成功.");
							}
							
							logger.info("视频日期[" + dateStr + "];链接地址[" + superLink + "];链接内容[" + content + "]的记录已经添加.");
							
							continue;
						}else
						{
							link = linkService.getLastRecordByCategoryId(CategoryConstant.BASKETBALL);
							
							if(link != null)
							{
								if(DateUtil.getIntMonth(link.getPlayTime()) < month)
								{
									year--;
								}
							}
							
							//加上年份
							dateStr = year + "年" + dateStr;
							
							Timestamp currentTimestamp = new Timestamp(System.currentTimeMillis());
							
							link = new TbVideoLink();
							
							link.setAddTime(currentTimestamp);
							link.setContent(content);
							link.setUpdateTime(currentTimestamp);
							link.setDetail(t.trim());
							link.setPlayTime(new Timestamp(DateUtil.parseChinaDate(dateStr).getTime()));
							link.setSuperLink(superLink);
							link.setVisited(0);
							link.setAddIp(GetIp.getLocalIp());
							link.setCategoryId(CategoryConstant.BASKETBALL);
							
							//添加记录
							linkService.addEntity(link);
							
							logger.info("视频日期[" + dateStr + "];链接地址[" + superLink + "];链接内容[" + content + "]的记录添加成功.");
						}
					}
				}
			}
		}
	}
}
